package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"pingce/core/config"
	"pingce/core/helper"
	"time"
)

func GetDb(ini_path ...string) *gorm.DB {
	mMap := config.GetDbConfig(ini_path...)

	hostName := mMap["hostname"]
	userName := mMap["username"]
	dataBase := mMap["database"]
	passWord := mMap["password"]
	hostPort := mMap["hostport"]
	charSet := mMap["charset"]

	dbStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", userName,
		passWord,
		hostName,
		hostPort,
		dataBase,
		charSet)
	db, err := gorm.Open(mysql.Open(dbStr), &gorm.Config{})
	if err != nil {
		helper.Dry(fmt.Errorf("连接数据库失败：%v", err.Error()))
	}

	pool, nil := db.DB()
	if err := pool.Ping(); err != nil {
		helper.Dry(fmt.Errorf("检测数据库连接失败：%v", err.Error()))
	}

	pool.SetMaxIdleConns(10)
	pool.SetMaxOpenConns(1000)
	pool.SetConnMaxLifetime(time.Second)
	pool.SetConnMaxIdleTime(time.Second)

	return db
}
